#include <unordered_map>
#include <regex>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>

#include "../source/Server.hpp"

#define DEFAULT_TIMEOUT 10

class Util
{
private:
    static bool Isalnum(char c)
    {
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }
    static char HexToDigtial(char c)
    {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'a' && c <= 'f')
            return c - 'a' + 10;
        if (c >= 'A' && c <= 'F')
            return c - 'A' + 10;
        return -1;
    }
public:
    Util() {}
    // 字符串分割，将src字符串按照sep字符串进行分割，得到各个字符串放入array中。最终返回字符串数量
    static size_t Split(const std::string& src, const std::string& sep, std::vector<std::string>* const array)
    {
        size_t pos = 0, offset = 0;
        while (offset < src.size())
        {
            pos = src.find(sep, offset);
            if (pos > offset)
                array->emplace_back(src.substr(offset, pos - offset));
            if (pos == std::string::npos) break; // 说明已经找完了
            offset = pos + sep.size();
        }
        return array->size();
        
    }
    // 读取文件内容
    static bool ReadFile(const std::string& filename, std::string* content)
    {
        std::ifstream ifs(filename, std::ios::binary);
        if (ifs.is_open() == false)
        {
            printf("%s open failed!\n", filename.c_str());
            return false;
        }
        size_t fsize = 0;
        ifs.seekg(0, ifs.end);
        fsize = ifs.tellg();
        ifs.seekg(0, ifs.beg);
        content->resize(fsize);
        ifs.read(&(*content)[0], fsize);
        if (ifs.good() == false)
        {
            printf("%s read failed!\n", filename.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }
    // 向文件写入数据
    static bool WriteFile(const std::string& filename, const std::string& content)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (ofs.is_open() == false)
        {
            printf("%s open failed!\n", filename.c_str());
            return false;
        }
        ofs.write(content.c_str(), content.size());
        if (ofs.good() == false)
        {
            printf("%s write failed!\n", filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }
    // URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中的特殊字符产生歧义
    // 编码格式：特殊字符的ascii值，转换成两个16进制字符，前缀% C++->C%2B%2B
    // 不编码的特色字符：RFC3986文档规定 .-_~字母和数字
    // RFC3689文档规定，编码格式 %HH
    // W3C标准中规定，查询字符串中的空格，需要编码为+，解码则是+转空格
    static std::string UrlEncode(const std::string& url, bool convert_spacetoplus)
    {
        std::string res;
        for (const auto& c : url)
        {
            if (c == '.' || c == '-' || c == '_' || c == '~' || Isalnum(c))
            {
                res += c;
                continue;
            }
            if (c == ' ' && convert_spacetoplus == true)
            {
                res += '+';
                continue;
            }
            // 剩下的字符都需要转成%HH格式
            char tmp[4] = { 0 };
            snprintf(tmp, sizeof(tmp), "%%%02X", c);
            res += tmp;
        }
        return std::move(res);
    }
    // URL解码
    static std::string UrlDecode(const std::string& url, bool convert_plustospace)
    {
        std::string res;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '%' && i + 2 < url.size())
            {
                char v1 = HexToDigtial(url[i + 1]);
                char v2 = HexToDigtial(url[i + 2]);
                char v = (v1 << 4) + v2;
                res += v;
                i += 2;
                continue;
            }
            if (url[i] == '+' && convert_plustospace == true)
            {
                res += ' ';
                continue;
            }
            res += url[i];
        }
        return std::move(res);
    }
    // 响应状态码的描述信息获取
    static std::string GetStatusDescribe(int statu)
    {
        auto it = statu_msg.find(statu);
        if (it != statu_msg.end())
            return it->second;
        
        return "Unknow";
    }
    // 根据文件后缀名获取文件mime
    static std::string GetMime(const std::string& filename)
    {
        
        size_t pos = filename.rfind('.');
        if (pos == std::string::npos)
            return "application/octet-stream";
        auto it = mime_msg.find(filename.substr(pos));
        if (it != mime_msg.end())
            return it->second;
        
        return "application/octet-stream";
    }
    // 判断文件是否是目录文件
    static bool IsDirectory(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;

        return S_ISDIR(st.st_mode);
    }
    // 判断一个文件是否是普通文件
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;

        return S_ISREG(st.st_mode);
    }
    // http请求的资源路径有效性判断
    static bool IsValidPath(const std::string& path)
    {
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);
        int level = 0;
        for (const auto& str : subdir)
        {
            if (str == "..")
            {
                level--;
                if (level < 0) return false; // 有任意一层跑到了Web根目录的外面就算无效
            }
            else
                level++;
        }
        return true;
    }
    ~Util() {}
private:
    static std::unordered_map<int, std::string> statu_msg;
    static std::unordered_map<std::string, std::string> mime_msg;
};

std::unordered_map<int, std::string> Util::statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> Util::mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

class HttpRequest
{
public:
    HttpRequest() 
    : _version("HTTP/1.1")
    {}

    void Reset()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        swap(_matches, match);
        _headers.clear();
        _params.clear();
    }

    void InsertHeader(const std::string& key, const std::string& value)
    {
        _headers.insert(std::make_pair(key, value));
    }
    bool FindHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    const std::string GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }

    std::string GetHeader(const std::string& key)
    {
        if (FindHeader(key) == false)
            return "";
        return _headers[key];
    }

    void Insertparam(const std::string& key, const std::string& value)
    {
        _params.insert(std::make_pair(key, value));
    }
    bool Findparam(const std::string& key)
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return false;
        return true;
    }
    std::string Getparam(const std::string& key)
    {
        if (Findparam(key) == false)
            return "";
        return _params[key];
    }

    size_t GetContentLength()
    {
        bool ret = FindHeader("Content-Length");
        if (!ret)
            return 0;
        std::string clen = GetHeader("Content-Length");
        return std::stol(clen);
    }
    bool IsKeepAlive() const
    {
        bool ret = FindHeader("Connection");
        if (ret && GetHeader("Connection") == "keep-alive")
            return true;
        return false;
    }
    ~HttpRequest() {}
public:
    std::string _method;
    std::string _path;
    std::string _version;
    std::string _body;
    std::smatch _matches;
    std::unordered_map<std::string, std::string> _headers;
    std::unordered_map<std::string, std::string> _params;
};

class HttpResponse
{
public:
    HttpResponse(int statu = 200)
    : _statu(statu)
    , _redirect_flag(false)
    {
    }
    void Reset()
    {
        _statu = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
    void InsertHeader(const std::string& key, const std::string& value)
    {
        _headers.insert(std::make_pair(key, value));
    }
    bool FindHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    std::string GetHeader(const std::string& key)
    {
        if (FindHeader(key) == false)
            return "";
        return _headers[key];
    }
    void SetContent(const std::string& body, const std::string& type = "text/html")
    {
        // _body = body;
        _body.assign(body.data(), body.size()); // 避免 COW 特性导致的写时复制
        InsertHeader("Content-Type", type);
    }
    void SetRedirect(const std::string& url, int statu = 302)
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }
    bool IsKeepAlive()
    {
        bool ret = FindHeader("Connection");
        if (ret && GetHeader("Connection") == "keep-alive")
            return true;
        return false;
    }
    ~HttpResponse() {}
    
public:
    int _statu;
    bool _redirect_flag;
    std::string _body;
    std::string _redirect_url;
    std::unordered_map<std::string, std::string> _headers;
};

#define MAX_LINE 8192

class HttpContent
{
public:
    typedef enum 
    {
        RECV_HTTP_ERROR,
        RECV_HTTP_LINE,
        RECV_HTTP_HEAD,
        RECV_HTTP_BODY,
        RECV_HTTP_OVER
    }HttpRecvStatu;
private:
    bool RecvHttpLine(Buffer* const buf)
    {
        if (_recv_statu != RECV_HTTP_LINE) return false;
        std::string line = buf->GetLine();
        if (line.size() == 0)
        {
            if (buf->GetReadableSize() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414; // URI TOO LONG
                return false;
            }
            return true;
        }
        if (line.size() > MAX_LINE)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414; // URI TOO LONG
            return false;
        }
        bool ret = ParseHttpLine(line);
        if (!ret)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; // BAD REQUEST
            return false;
        }
        _recv_statu = RECV_HTTP_HEAD;
        return true;
    }
    bool ParseHttpLine(const std::string& line)
    {
        // Http请求行格式：GET /a/login?user=zhangsan&pass=123456 HTTP/1.1\r\n
        std::smatch matches;
        std::regex e("(GET|POST|HEAD|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        bool ret = std::regex_match(line, matches, e);
        if (ret == false)
        {
            return false;
        }
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        _request._path = Util::UrlDecode(matches[2], false);
        _request._version = matches[4];
        // 查询字符串进行进一步解析
        std::vector<std::string> query_string_array;
        std::string query_string = matches[3];
        // 查询字符串的格式 key=value&key=value...，先以&符号进行分割，得到各个子串
        Util::Split(query_string, "&", &query_string_array);
        for (const auto& str : query_string_array)
        {
            size_t pos = str.find('=');
            if (pos == std::string::npos)
            {
                return false;
            }
            _request.Insertparam(Util::UrlDecode(str.substr(0, pos), true), Util::UrlDecode(str.substr(pos + 1), true));
        }
        return true;
    }
    bool RecvHttpHead(Buffer* const buf)
    {
        if (_recv_statu != RECV_HTTP_HEAD) return false;
        while (1)
        {
            std::string line = buf->GetLine();
            if (line.size() == 0)
            {
                if (buf->GetReadableSize() > MAX_LINE)
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414; // URI TOO LONG
                    return false;
                }
                return true;
            }
            if (line.size() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414; // URI TOO LONG
                return false;
            }
            if (line == "\n" || line == "\r\n") // 遇到空行停止获取
                break;
            bool ret = ParseHttpHead(line);
            if (!ret)
                return false;
        }
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }
    bool ParseHttpHead(const std::string& line)
    {
        // line只有一行
        // key: val\r\n
        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; // BAD REQUEST
            return false;
        }
        // 记得末尾的\r\n不要存入
        _request.InsertHeader(line.substr(0, pos), line.substr(pos + 2, line.size() - pos - 4));
        return true;
    }
    bool RecvHttpBody(Buffer* const buf)
    {
        if (_recv_statu != RECV_HTTP_BODY) return false;
        // 1.获取正文长度
        size_t content_len = _request.GetContentLength();
        if (content_len == 0)
        {
            // 没有正文，则请求接收解析完毕
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        // 2.当前已经接受了多少正文 _request._body
        size_t real_len = content_len - _request._body.size(); // 实际还需要接受的正文长度
        // 3.接收正文放到body中，但是也要考虑当前缓冲区中的数据，是否是全部的正文
        // 3.1缓冲区中数据，包含了当前请求的所有正文，则取出所需的数据
        if (buf->GetReadableSize() >= real_len)
        {
            _request._body.append(buf->GetReadAddr(), real_len);
            buf->MoveBackReadOffset(real_len);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        // 3.2缓冲区中数据，无法满足当前我们的正文需要，数据不足，取出数据，然后等待新数据到来
        _request._body.append(buf->GetReadAddr(), buf->GetReadableSize());
        buf->MoveBackReadOffset(buf->GetReadableSize());
        return true;
    }
public:
    HttpContent()
    : _resp_statu(200)
    , _recv_statu(RECV_HTTP_LINE)
    {}
    void Reset()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
        _request.Reset();
    }
    int GetResponseStatu()
    {
        return _resp_statu;
    }
    HttpRecvStatu GetRecvStatu()
    {
        return _recv_statu;
    }
    HttpRequest& GetRequest()
    {
        return _request;
    }
    // 接收并解析http请求
    void RecvHttpRequest(Buffer* const buf)
    {
        switch(_recv_statu)
        {
            case RECV_HTTP_LINE: RecvHttpLine(buf);
            case RECV_HTTP_HEAD: RecvHttpHead(buf);
            case RECV_HTTP_BODY: RecvHttpBody(buf);
        }
    }
    ~HttpContent() {}
public:
    int _resp_statu;
    HttpRecvStatu _recv_statu;
    HttpRequest _request;
};

class HttpServer
{
using Handler = std::function<void(const HttpRequest&, HttpResponse*)>;
using Handlers = std::vector<std::pair<std::regex, Handler>>;
private:
    void ErrorHandler(const HttpRequest& req, HttpResponse* const resp)
    {
        //1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(resp->_statu);
        body += " ";
        body += Util::GetStatusDescribe(resp->_statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        //2. 将页面数据，当作响应正文，放入rsp中
        resp->SetContent(body, "text/html");
    }
    // 序列化并发送
    void WriteResponse(const Connection::connection_ptr& conn, HttpRequest& req, HttpResponse* const resp)
    {
        // 1.完善头部字段
        if (req.IsKeepAlive())
            resp->InsertHeader("Connection", "keep-alive");
        else
            resp->InsertHeader("Connection", "close");
        if (!resp->_body.empty() && !resp->FindHeader("Content-Length"))
        {
            resp->InsertHeader("Content-Length", std::to_string(resp->_body.size()));
        }
        if (!resp->_body.empty() && !resp->FindHeader("Content-Type"))
            resp->InsertHeader("Content-Type", "application/octet-stream");
        if (resp->_redirect_flag)
            resp->InsertHeader("Location", resp->_redirect_url);
        // 2.将resp中的要素，按照http协议格式进行组织
        std::stringstream resp_str;
        resp_str << req._version << " " << std::to_string(resp->_statu) << " " << Util::GetStatusDescribe(resp->_statu) << "\r\n";
        for (const auto& head : resp->_headers)
        {
            resp_str << head.first << ": " << head.second << "\r\n";
        }
        resp_str << "\r\n";
        resp_str << resp->_body;
        // 3.发送数据
        conn->Send(resp_str.str().c_str(), resp_str.str().size());
    }
    bool IsFileHandler(const HttpRequest& req)
    {
        // 1.必须设置了静态资源根目录
        if (_basedir.empty())
            return false;
        // 2.请求方法必须是GET/HEAD请求方法
        if (req._method != "GET" && req._method != "HEAD")
            return false;
        // 3.请求的资源路径必须是一个合法路径
        if (!Util::IsValidPath(req._path))
            return false;
        // 4.请求的资源必须存在
        //    有一种请求比较特殊 纯粹的相对根目录/，这种情况给后边默认追加一个index.html
        // 不要忘了前缀的相对根目录 /image/a.png -> ./wwwroot/image/a.png
        std::string req_path = _basedir + req._path; // 为了避免直接修改请求的资源路径，因此定义一个临时对象
        if (req._path.back() == '/')
            req_path += "index.html";
        if (!Util::IsRegular(req_path))
            return false;
        return true;
    }
    // 静态资源的请求处理——将静态资源文件的数据读取出来，放到resp的_body中，并设置mime
    bool FileHandler(const HttpRequest& req, HttpResponse* const resp)
    {
        std::string req_path = _basedir + req._path; // 为了避免直接修改请求的资源路径，因此定义一个临时对象
        if (req._path.back() == '/')
            req_path += "index.html";
        bool ret = Util::ReadFile(req_path, &resp->_body);
        if (!ret)
            return false;
        std::string mime = Util::GetMime(req_path);
        resp->InsertHeader("Content-Type", mime);
        return true;
    }
    // 功能性的请求处理
    void Dispatcher(HttpRequest& req, HttpResponse* const resp, const Handlers& handlers)
    {
        // 正则表达式 & 处理函数
        for (const auto& handler : handlers)
        {
            const std::regex& re = handler.first;
            const Handler& functor = handler.second;
            bool ret = std::regex_match(req._path, req._matches, re);
            if (!ret) continue;
            functor(req, resp);
            return;
        }
        resp->_statu = 404;
    }
    void Route(HttpRequest& req, HttpResponse* const resp)
    {
        // 1.对请求进行分辨，是一个功能性请求or静态资源请求
        if (IsFileHandler(req))
        {
            FileHandler(req, resp);
            return;
        }
        if (req._method == "GET" || req._method == "HEAD")
            Dispatcher(req, resp, _get_route);
        else if (req._method == "POST")
            Dispatcher(req, resp, _post_route);
        else if (req._method == "PUT")
            Dispatcher(req, resp, _put_route);
        else if (req._method == "DELETE")
            Dispatcher(req, resp, _delete_route);
        else
            resp->_statu = 405; // Method not allowed
    }
    // 设置上下文
    void OnConnected(const Connection::connection_ptr& conn)
    {
        conn->SetContext(HttpContent());
        DEBUG_LOG("new connection %p", conn.get());
    }
    // 用于进行缓冲区数据解析+处理
    void OnMessage(const Connection::connection_ptr& conn, Buffer* buf)
    {
        while (buf->GetReadableSize() > 0)
        {
            // 1.获取上下文
            HttpContent* context = conn->GetContext()->Get<HttpContent>();
            // 2.通过上下文对缓冲区数据进行解析，得到HttpRequest对象
            // 2.1如果缓冲区的数据解析失败，就直接回复出错响应
            // 2.2如果解析正常，且请求已经获取完毕，才开始去进行处理
            context->RecvHttpRequest(buf);
            HttpRequest& req = context->GetRequest();
            HttpResponse resp(context->GetResponseStatu());
            if (context->GetResponseStatu() >= 400)
            {
                // 进行错误响应，关闭连接
                ErrorHandler(req, &resp); // 填充一个错误显示页面数据到resp中
                WriteResponse(conn, req, &resp); // 组织响应发送给客户端
                // 这个操作很重要，因为此时出错了，说明recvStatu是错误的，它就不会继续在缓冲区取数据，而Shutdown
                // 函数发现缓冲区数据没取完，又会调用OnMessage，导致死循环，应该重置context内容，让其把数据取完
                context->Reset();
                buf->MoveBackReadOffset(buf->GetReadableSize()); // 出错了，就把缓冲区数据清空
                conn->ShutDown(); // 关闭连接
                return;
            }
            if (context->GetRecvStatu() != HttpContent::RECV_HTTP_OVER)
            {
                // 当前请求还没有接收完整,则退出，等新数据到来再重新继续处理
                return;
            }
            // 3.请求路由+业务处理
            Route(req, &resp);
            // 4.对HttpResponse进行组织发送
            WriteResponse(conn, req, &resp);
            // 重置上下文
            context->Reset();
            // 5.根据长短连接判断是否关闭或继续处理
            if (!resp.IsKeepAlive()) conn->ShutDown(); // 短连接则直接关闭
        }   
    }
public:
    HttpServer(int port, int timeout = DEFAULT_TIMEOUT)
    : _server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    void SetBasedir(const std::string& path)
    {
        bool ret = Util::IsDirectory(path);
        assert(ret == true);
        _basedir = path;
    }
    // 设置/添加，请求（请求的正则表达式）与处理函数的映射关系
    void Get(const std::string& pattern, const Handler& handler)
    {
        _get_route.emplace_back(std::make_pair(std::regex(pattern), handler));
    }
    void Post(const std::string& pattern, const Handler& handler)
    {
        _post_route.emplace_back(std::make_pair(std::regex(pattern), handler));
    }
    void Put(const std::string& pattern, const Handler& handler)
    {
        _put_route.emplace_back(std::make_pair(std::regex(pattern), handler));
    }
    void Delete(const std::string& pattern, const Handler& handler)
    {
        _delete_route.emplace_back(std::make_pair(std::regex(pattern), handler));
    }
    void SetThreadCount(uint32_t count)
    {
        _server.SetThreadCount(count);
    }
    void Listen()
    {
        _server.Start();
    }
    ~HttpServer() {}
private:
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir;
    TcpServer _server;
};